package Utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import BaseDBEntity.DbProperties;
import BaseDBEntity.KeyColum;
import BaseDBEntity.TableDescription;

public class ParseAnnotation {

	/**
	 * 解析方法注解
	 * 
	 * @param clazz
	 */
	public static <T> DbProperties parseMethod(Class<T> clazz) {
		try {

			DbProperties db = new DbProperties();

			TableDescription tableAnnotation = clazz
					.getAnnotation(TableDescription.class);
			if (tableAnnotation != null) {
				String strTableName = tableAnnotation.tableName();

				if (!StringUtils.isEmpty(strTableName)) {

					db.setTableName(strTableName);
				} else {
					db.setTableName(clazz.getSimpleName());
				}
				
				String strOrderBy = tableAnnotation.orderBy();
				
				if (!StringUtils.isEmpty(strOrderBy)) {

					db.setOrderBy(strOrderBy);
				}
				

			}

			List<String> list = new ArrayList<String>();
			Field[] fields = clazz.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				field.setAccessible(true);

				KeyColum column = field.getAnnotation(KeyColum.class);
				if (column != null) {
					String strKeyName =  column.keyName();
					if (!StringUtils.isEmpty(strKeyName)) {
						
						list.add(strKeyName);
					
					}
				}
			}
			if(list.size()>0)
			{
				db.setPrimaryKeyNames(list);
			}

			return db;

		} catch (Exception ex) {

		}

		return null;
	}

}